package cemetery.dao;
/**
 * dao层工具类
 * 1.获取数据库连接
 * 2.关闭数据库连接
 * 3.增删改的通用方法
 * 
 * @author Administrator
 *
 */

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;





public class BaseDao {
	
	private static String url = "";
	private static String classname = "";
	private static String username = "";
	private static String pwd = "";
	
	private Connection conn = null;
	
	static {
		//java提供的读取属性文件的对象
		Properties prop = new Properties();
		InputStream is = BaseDao.class.getClassLoader()
				.getResourceAsStream("db.properties");
		try {
			prop.load(is);
			classname = prop.getProperty("driverName");
			url = prop.getProperty("url");
			username = prop.getProperty("username");
			pwd = prop.getProperty("pwd");
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取数据库连接，当数据库连接不可用的情况下，重新获取
	 * @return
	 */
	public Connection getconnection() {
		
		try {
			if (conn == null||conn.isClosed()) {
				Class.forName(classname);
				conn=DriverManager.getConnection(url,username,pwd);
			}
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return conn;
	}
	public void closeAll(Connection conn,Statement stmt,ResultSet rs) {
		try {
			if (rs!=null) {
				rs.close();
			}
			if (stmt!=null) {
				stmt.close();
			}
			if (conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
	}
	/**
	 * 增删改通用方法
	 * @param psql 预编译sql，可能有？可能没有？
	 * @param params 参数数组 需要和psql中的？个数、顺序保持一致
	 * @return
	 */
	public int executeUpdate(String psql,Object[] params) {
		int count = 0;
		PreparedStatement pstmt = null;
		try {
			conn = getconnection();
			pstmt = conn.prepareStatement(psql);
			if (params!=null&&params.length>0) {
				for (int i = 0; i < params.length; i++) {
					pstmt.setObject(i+1, params[i]);				
				}
			}
			System.out.println();
			count = pstmt.executeUpdate();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			closeAll(conn, pstmt, null);
		}
		return count;
	}

}
